
/*库引用*/
#include <Windows.h>
#include <mmsystem.h>
#include <graphics.h>
#include <iostream>
#include <string>
#include <stack>
#include <random>
#include <ctime>
#include <vector>
#include <cstdlib>
#include <conio.h>
#include <tuple>
#pragma comment(lib, "Winmm.lib")
using namespace std;

/*颜色分量宏定义*/
#define PA(color) (((color)&0xFF000000) >> 24)
#define PB(color) (((color)&0x00FF0000) >> 16)
#define PG(color) (((color)&0x0000FF00) >> 8)
#define PR(color) (((color)&0x000000FF))
/*计算混合颜色宏定义*/
#define ARGB(s, d, a) RGB((PR(s) * a + PR(d) * (255 - a)) >> 8, \
                          (PG(s) * a + PG(d) * (255 - a)) >> 8, \
                          (PB(s) * a + PB(d) * (255 - a)) >> 8)

// 全局变量定义
const int WIDTH = 1620;        // 窗口宽度
const int HEIGHT = 900;        // 窗口高度
const int CELL_SIZE = 60;      // 迷宫单元格大小
const int PEOPLE_SIZE = 60;
const int FrameWidth = 240;
const int FrameHeight = 60;
const int length = 200;

std::stack<int> pageStack;
int currentPage = 0;
int LevelSelect = 0;
int boxWidth = 300;
int boxHeight = 100;
int skillOne = 0;
int lastDirection = 0;         // 添加一个变量用于记录最后一次移动的方向
int whatDirection = 0;			//运动方向
int STAGES = 0;
int maze[100][100];			   // 迷宫地图分块
int people_x, people_y;
int monsterX, monsterY;
int entryX, entryY, exitX, exitY;
int mazeWidth = WIDTH / CELL_SIZE;
int mazeHeight = HEIGHT / CELL_SIZE;


IMAGE img, img2, people, brick, brick2,  player_head;
IMAGE chara, player1, player2;
IMAGE *players1[100], * players2[100], * players_m[6], * effect_m[6],* charas[100];
IMAGE cha, bag, back, window, plusimage, intro, name;
IMAGE beginmusic, closemusic, begingame, gameintro, returnback, windowback;
IMAGE photo[4],word[5], map_bricks[4], map[10], monster[4];

bool musicPlaying = true;
bool attackIsDodged = false;
bool attackIsCritical = false;
bool energyShieldActive = false;
bool returnToMain = false;
bool isWindowBack = false;
bool inInventory = false;       // 是否在背包界面
bool showCharacterInfo = true;  // 是否显示角色信息
bool battleInProgress = false;  // 标志变量，表示是否在对战中
bool visited[100][100];			// 用于标记已访问的单元格
bool isInventoryOpen = false;
bool usingSkill1 = false;
bool usingSkill2 = false;
bool haveLvDot = false;
bool isIntroPage = false;
bool showCrit = false;
bool showDodge = false;
bool showSkill1 = false;
bool showSkill2 = false;
bool showSkill3 = false;
bool showKill = false;
static int requiredExp[] ={ 30, 50, 90, 180, 360, 720, 1440, 3000, 10000 };
ExMessage msg;

// 角色属性和处理
struct Character
{
	std::string name;
	int level;
	int health;
	int maxHealth;
	int mana;
	int maxMana;
	int minAttack;
	int maxAttack;
	int defense;
	double critChance;
	double critDamage;
	double dodgeChance;
	int experience;
	int lvadddot = 0;
	int money;
	Character(const std::string& charName, int charLevel, int charHealth, int charMaxHealth,
		int charMana, int charMaxMana, int charMinAttack, int charMaxAttack, int charDefense,
		double charCritChance, double charCritDamage, double charDodgeChance)
		: name(charName), level(charLevel), health(charHealth), maxHealth(charHealth), mana(charMana),
		maxMana(charMaxMana), minAttack(charMinAttack), maxAttack(charMaxAttack), defense(charDefense),
		critChance(charCritChance), critDamage(charCritDamage), dodgeChance(charDodgeChance),
		experience(0), lvadddot(0),money(0) {}

	void takeDamage(const Character& enemy)
	{
		// 生成一个随机数
		std::mt19937 rng(static_cast<unsigned int>(time(nullptr)));
		std::uniform_real_distribution<double> dist(0.0, 1.0);

		double enemyAttack = dist(rng) * (enemy.maxAttack - enemy.minAttack) + enemy.minAttack;

		// 防御力生效逻辑
		if (level >= enemy.level)
			defense *= (1 + (level - enemy.level) / 10);
		else
			defense /= 2;

		// 计算伤害初始值
		double damage = static_cast<double>(enemyAttack - defense);

		// 计算攻击是否被闪避
		if (dist(rng) < dodgeChance)
		{
			showDodge = true;
			attackIsDodged = true;
			return;
		}

		// 判定是否暴击
		if (dist(rng) < enemy.critChance) // 使用敌人的暴击率
		{
			showCrit = true;
			attackIsCritical = true;
			damage *= enemy.critDamage; // 使用敌人的爆伤率
		}
		if (damage < 1.0)
			damage = 1.0;

		// 判断三技能状态
		if (energyShieldActive && mana != 0)
		{
			mana -= static_cast<int>(damage / 3);
			if (mana < 0)
				mana = 0;
		}
		else
		{
			health -= static_cast<int>(damage);
			if (health < 0)
				health = 0;
		}
	}

	void useSkill1()
	{
		if (mana >= 10 * static_cast<int>((1 + static_cast<double>(level) / 10)))
		{
			mana -= 10 * static_cast<int>((1 + static_cast<double>(level) / 10)); // 先减去蓝量
			usingSkill1 = true;                                                   // 设置技能1触发标志
		}
		else
		{
			// 输出蓝量不够的提示
		}
	}

	void useSkill2(Character& target)
	{
		std::mt19937 rng(static_cast<unsigned int>(time(nullptr)));
		std::uniform_real_distribution<double> dist(0.0, 1.0);
		double endAttack = dist(rng) * (maxAttack - minAttack) + minAttack;

		/*减少自身生命值*/
		health = health / 2;
		// 计算基础伤害

		double damage = 5 * endAttack;
		if (dist(rng) < critChance)
		{
			attackIsCritical = true;
			damage *= critDamage; // 计算爆伤
		}
		// 减少目标生命值
		if (damage < 1.0)
			damage = 1.0;
		target.health -= static_cast<int>(damage);
		// 生命值增加操作
		if (target.health <= 0)
		{
			target.health = 0;
			health += maxHealth / 4;
			if (health > maxHealth)
			{
				health = maxHealth;
			}
		}
	}

	void useSkill3()
	{
		if (!energyShieldActive)
		{
			energyShieldActive = true;
		}
		else
		{
			energyShieldActive = false;
		}
	}

	void levelUp()
	{
		if (level < 10 && experience >= requiredExp[level - 1])
		{
			experience -= requiredExp[level - 1];
			level++;

			maxHealth += 100 * (level - 1);
			maxMana += 30 * (level - 1);
			minAttack += 5;
			maxAttack += 5;
			defense += 5;

			health = maxHealth;
			mana = maxMana;

			lvadddot += 1;
			haveLvDot = true;
		}
	}

	void gainExperience(const Character enemy)
	{
		if(health>0)
		{
			int gainedExperience = 10 + enemy.level * 5;
			experience += gainedExperience;
			money += gainedExperience * 2;
		}
	}

	void printAttribute(int x, int y)
	{
		settextstyle(36, 0, _T("黑体"));

		std::wstring nameStr = L"姓名: " + std::wstring(name.begin(), name.end());
		std::wstring healthStr = L"生命值: " + std::to_wstring(health) + L"/" + std::to_wstring(maxHealth);
		std::wstring manaStr = L"魔法值: " + std::to_wstring(mana) + L"/" + std::to_wstring(maxMana);
		std::wstring minAttackStr = L"最小攻击: " + std::to_wstring(minAttack);
		std::wstring maxAttackStr = L"最大攻击: " + std::to_wstring(maxAttack);
		std::wstring defenseStr = L"防御力: " + std::to_wstring(defense);
		std::wstring critChanceStr = L"暴击率: " + std::to_wstring(critChance);
		std::wstring critDamageStr = L"爆伤率: " + std::to_wstring(critDamage);
		std::wstring dodgeChanceStr = L"闪避率: " + std::to_wstring(dodgeChance);
		std::wstring moneyStr = L"金币: " + std::to_wstring(money);

		const wchar_t* tcharNameStr = nameStr.c_str();
		const wchar_t* tcharHealthStr = healthStr.c_str();
		const wchar_t* tcharManaStr = manaStr.c_str();
		const wchar_t* tcharMinAttackStr = minAttackStr.c_str();
		const wchar_t* tcharMaxAttackStr = maxAttackStr.c_str();
		const wchar_t* tcharDefenseStr = defenseStr.c_str();
		const wchar_t* tcharCritChanceStr = critChanceStr.c_str();
		const wchar_t* tcharCritDamageStr = critDamageStr.c_str();
		const wchar_t* tcharDodgeChanceStr = dodgeChanceStr.c_str();
		const wchar_t* tcharmoneyStr = moneyStr.c_str();

		outtextxy(x + 45, y + 10, tcharNameStr);
		outtextxy(x + 45, y + 45, tcharHealthStr);
		outtextxy(x + 45, y + 80, tcharManaStr);
		outtextxy(x + 45, y + 115, tcharMinAttackStr);
		outtextxy(x + 45, y + 150, tcharMaxAttackStr);
		outtextxy(x + 45, y + 185, tcharDefenseStr);
		outtextxy(x + 45, y + 220, tcharCritChanceStr);
		outtextxy(x + 45, y + 255, tcharCritDamageStr);
		outtextxy(x + 45, y + 290, tcharDodgeChanceStr);
		outtextxy(x + 45, y + 325, tcharmoneyStr);

		if (haveLvDot)
		{
			int py = y;
			for (int i = 1; i < 9; i++)
			{
				putimage(x + 5, py + 50, &plusimage);
				py += 35;
			}
		}
	}
};

// 初始化角色
Character cyx("cyx", 1, 200, 200, 50, 50, 20, 40, 5, 0.1, 1.5, 0.2);
Character monster0("皮卡丘", 1, 250, 100, 0, 0, 15, 20, 10, 0.2, 1.5, 0);
Character monster1("小火龙", 1, 100, 100, 0, 0, 1, 100, 0, 0.05, 1.5, 0);
Character monster2("妙蛙种子", 1, 150, 150, 0, 0, 5, 15, 10, 0.9, 1.2, 0);
Character monster3("杰尼龟", 1, 600, 600, 0, 0, 0, 10, 10, 0, 0, 0.4);

// 函数定义
void MyGame();
void loadImagesAndMusic();
void DrawStartGamePage(); // 绘制开始游戏的界面
void OperatorSelectPage();
void DrawLevelSelectionPage(IMAGE& img);           // 绘制关卡选择界面
void HandleMouseClick(ExMessage& msg, IMAGE& img); // 在开始界面检测鼠标点击
void SelectMusic();                                // 选择音乐
void BeginGame(int diff, int monstersnum);
void DrawGame1Screen();
void InitializePlayerAndResources();
void CharacterMovementLogic1();
void GameLoop();
void movementCheck(int beginX, int beginY, int i);
void HandleKeyboardInput();
void DrawGameGraphics(int beginX, int beginY, int length, int i, IMAGE* map);
int Operator1(char a, char b);
void PutAlphaImage(int x, int y, IMAGE* pSrcImage);
void PUTAlphaImage(IMAGE* pDstImage, int x, int y, IMAGE* pSrcImage);
void cropImage(IMAGE* inputImage, int numCols, int numRows, IMAGE* a[]);
IMAGE* mirrorImage(IMAGE* pImg);
void DrawCharacterInfo();
void attackCheck(int beginX, int beginY, int i);
void generateMaze(int complexity);
bool isWall(int x, int y);
bool hasPathBetween(int startX, int startY, int endX, int endY);
void drawMaze(int entryX, int entryY, int exitX, int exitY);
void drawMap(int complexity, int monsternum);
void makeMonsters(int num);
bool IsPlayerNearMonster();
void BattleLoop(int beginX, int beginY, Character monsters);
void drawMonster();
void saveNewImage(int beginX, int beginY, int i);
void PlusKeyClick();
bool IsPlayerNearExit();
void drawPreMap();
void prepareGame();
void prepareLoop();
void CharacterMovementLogic2();
void showMassage();

int APIENTRY WinMain(
	_In_ HINSTANCE hInstance,
	_In_opt_ HINSTANCE hPrevInstance,
	_In_ LPSTR lpCmdLine,
	_In_ int nShowCmd)
{
	// 加载图片
	loadImagesAndMusic(); 

	// 初始化视图
	initgraph(WIDTH, HEIGHT);

	// 绘制开始游戏界面
	DrawStartGamePage();

	// 绘制关卡选择界面及其操作
	OperatorSelectPage();

	// 初始化人物和资源
	InitializePlayerAndResources();

	//开始游戏
	MyGame();

	while (1);
	closegraph();
	return 0;
}
void MyGame() {
	while (1)
	{
		// 准备游戏
		prepareGame();

		if (returnToMain)
		{
			// 返回到 WinMain 的开头
			returnToMain = false; // 重置标志
			STAGES = 0;
			continue;
		}
		STAGES++;
		// 开始游戏
		BeginGame(2, 18 + 3 + STAGES);
	}
}
void loadImagesAndMusic()
{
	// 初始化并打开音乐
	mciSendString(L"open bg.mp3 alias mymusic", NULL, 0, NULL);
	mciSendString(L"play mymusic repeat", NULL, 0, NULL);
	// 加载图片
	loadimage(&img, _T("images/bgbegin.png"), WIDTH, HEIGHT);
	loadimage(&img2, _T("images/bg3.png"), WIDTH, HEIGHT);
	loadimage(&brick, _T("images/brick2.png"), 50, 50);
	loadimage(&brick2, _T("images/brick.png"), 50, 50);
	loadimage(&monster[0], _T("images/0.png"), CELL_SIZE, CELL_SIZE);
	loadimage(&monster[1], _T("images/1.png"), CELL_SIZE, CELL_SIZE);
	loadimage(&monster[2], _T("images/2.png"), CELL_SIZE, CELL_SIZE);
	loadimage(&monster[3], _T("images/3.png"), CELL_SIZE, CELL_SIZE);
	loadimage(&chara, _T("images/Run_Sheet.png"), PEOPLE_SIZE * 2 * 6, PEOPLE_SIZE * 2);
	loadimage(&player1, _T("images/player1.png"), PEOPLE_SIZE * 2 * 6, PEOPLE_SIZE * 2 * 6);
	loadimage(&player2, _T("images/player2.png"), PEOPLE_SIZE * 2 * 4, PEOPLE_SIZE * 2 * 4);
	loadimage(&player_head, _T("images/3.png"), CELL_SIZE, CELL_SIZE);
	loadimage(&map_bricks[0], _T("images/brick.png"), CELL_SIZE, CELL_SIZE);
	loadimage(&map_bricks[2], _T("images/brick2.png"), CELL_SIZE, CELL_SIZE);
	loadimage(&map_bricks[3], _T("images/bg.png"), CELL_SIZE, CELL_SIZE);
	loadimage(&map_bricks[1], _T("images/bg2.png"), CELL_SIZE, CELL_SIZE);
	loadimage(&cha, _T("images/cha.png"), CELL_SIZE, CELL_SIZE);
	loadimage(&bag, _T("images/bag.png"), CELL_SIZE * 2, CELL_SIZE * 2);
	loadimage(&back, _T("images/back.png"), CELL_SIZE * 2, CELL_SIZE * 2);
	loadimage(&window, _T("images/bg.png"), WIDTH / 2, HEIGHT / 2);
	loadimage(&plusimage, _T("images/plus.png"), 30, 30);
	loadimage(&intro, _T("images/introduce.png"), WIDTH / 2, HEIGHT * 2 / 3);
	loadimage(&windowback, _T("images/windowback.png"), WIDTH / 2, HEIGHT * 2 / 3);
	loadimage(&begingame, _T("images/开始游戏.png"), FrameWidth, FrameHeight);
	loadimage(&beginmusic, _T("images/开启音乐.png"), FrameWidth, FrameHeight);
	loadimage(&closemusic, _T("images/关闭音乐.png"), FrameWidth, FrameHeight);
	loadimage(&gameintro, _T("images/游戏介绍.png"), FrameWidth, FrameHeight);
	loadimage(&photo[0], _T("images/第一关.png"), boxWidth, boxHeight);
	loadimage(&photo[1], _T("images/第二关.png"), boxWidth, boxHeight);
	loadimage(&photo[2], _T("images/第三关.png"), boxWidth, boxHeight);
	loadimage(&photo[3], _T("images/第四关.png"), boxWidth, boxHeight);
	loadimage(&returnback, _T("images/返回.png"), 100, 40);
	loadimage(&word[0], _T("images/word0.png"), FrameWidth, FrameHeight * 3);
	loadimage(&word[1], _T("images/word1.png"), FrameWidth* 3, FrameHeight * 4);
	loadimage(&word[2], _T("images/word2.png"), FrameWidth * 3, FrameHeight * 5);
}
void DrawStartGamePage()
{
	// 加载背景图片
	cleardevice();
	putimage(0, 0, &img);
	// 绘制音乐管理按钮
	if (musicPlaying)
	{
		putimage(WIDTH / 2 - 85, HEIGHT * 2 / 3 + 5, &closemusic);
	}
	else
	{
		putimage(WIDTH / 2 - 85, HEIGHT * 2 / 3 + 5, &beginmusic);
	}

	// 绘制开始游戏按键
	putimage(WIDTH / 2 - 85, HEIGHT * 1 / 2 + 5, &begingame);

	// 绘制游戏介绍按键
	putimage(WIDTH / 2 - 85, HEIGHT * 5 / 6 + 5, &gameintro);
}
void OperatorSelectPage()
{
	while (1)
	{
		if (peekmessage(&msg, EM_MOUSE))
		{
			HandleMouseClick(msg, img);
		}
		if (currentPage >= 2)
			break;
	}
}
void DrawLevelSelectionPage(IMAGE& img)
{
	cleardevice();
	putimage(0, 0, &img);
	setlinecolor(RGB(255, 255, 255));

	pageStack.push(currentPage);
	currentPage = 1;

	// 绘制关卡选择界面的代码
	int pageWidth = WIDTH;
	int pageHeight = HEIGHT;
	int margin = 50; // 间距

	int centerX = pageWidth / 2;
	int centerY = pageHeight / 2;

	// 绘制第一关文字框
	int x1 = centerX - boxWidth / 2;
	int y1 = centerY - boxHeight / 2 - boxHeight - margin;
	putimage(x1, y1, &photo[0]);

	// 绘制第二关文字框
	int x2 = centerX - boxWidth / 2;
	int y2 = centerY - boxHeight / 2;
	putimage(x2, y2, &photo[1]);

	// 绘制第三关文字框
	int x3 = centerX - boxWidth / 2;
	int y3 = centerY - boxHeight / 2 + boxHeight + margin;
	putimage(x3, y3, &photo[2]);

	// 绘制第四关文字框
	int x4 = centerX - boxWidth / 2;
	int y4 = centerY - boxHeight / 2 + 2 * (boxHeight + margin);
	putimage(x4, y4, &photo[3]);

	// 绘制返回框
	putimage(60, 60, &returnback);
}
void SelectMusic()
{
	// 加载背景图片
	cleardevice();
	putimage(0, 0, &img);

	// 绘制音乐管理按钮
	if (musicPlaying)
	{
		putimage(WIDTH / 2 - 85, HEIGHT * 2 / 3 + 5, &beginmusic);
		mciSendString(L"pause mymusic", NULL, 0, NULL);
	}
	else
	{
		putimage(WIDTH / 2 - 85, HEIGHT * 2 / 3 + 5, &closemusic);
		mciSendString(L"play mymusic", NULL, 0, NULL);
	}
	musicPlaying = !musicPlaying;
	// 绘制开始游戏按键
	putimage(WIDTH / 2 - 85, HEIGHT * 1 / 2 + 5, &begingame);

	// 绘制游戏介绍按键
	putimage(WIDTH / 2 - 85, HEIGHT * 5 / 6 + 5, &gameintro);
}
void DrawIntroPage()
{
	if (!isIntroPage)
	{
		int windowX = (WIDTH - window.getwidth()) / 2;   // 计算窗口的X坐标，使其居中
		int windowY = (HEIGHT - window.getheight()) / 2; // 计算窗口的Y坐标，使其居中

		putimage(windowX, windowY, &intro);

		while (1)
		{
			if (GetAsyncKeyState('B') & 0x8000)
			{
				DrawStartGamePage();
				isIntroPage = false;
				break;
			}
		}
	}
}
void HandleMouseClick(ExMessage& msg, IMAGE& img)
{
	switch (msg.message)
	{
	case WM_LBUTTONDOWN:
		if (currentPage == 0 && msg.x > WIDTH / 2 - FrameWidth / 2 && msg.x < WIDTH / 2 + FrameWidth / 2 &&
			msg.y > HEIGHT * 2 / 3 && msg.y < HEIGHT * 2 / 3 + FrameHeight)
		{
			SelectMusic();
			// 点击音乐按钮的操作
		}
		else if (currentPage == 0 && msg.x > WIDTH / 2 - FrameWidth / 2 && msg.x < WIDTH / 2 + FrameWidth / 2 &&
			msg.y > HEIGHT * 5 / 6 && msg.y < HEIGHT * 5 / 6 + FrameHeight)
		{
			// 进入游戏介绍的操作
			DrawIntroPage();
		}
		else if (currentPage == 0 && msg.x > WIDTH / 2 - FrameWidth / 2 && msg.x < WIDTH / 2 + FrameWidth / 2 &&
			msg.y > HEIGHT * 1 / 2 && msg.y < HEIGHT * 1 / 2 + FrameHeight)
		{
			// 进入关卡选择界面的操作
			DrawLevelSelectionPage(img);
		}
		else if (msg.x > 60 && msg.x < 160 && msg.y > 60 && msg.y < 100)
		{
			if (currentPage == 1)
			{
				// 返回按钮被点击，在栈中弹出前一个页面状态
				currentPage = pageStack.top();
				pageStack.pop();

				if (currentPage == 0)
				{
					DrawStartGamePage();
				}
			}
		}
		else if (currentPage == 1)
		{
			int centerX = WIDTH / 2;
			int centerY = HEIGHT / 2;
			int margin = 50;

			int boxX1 = centerX - boxWidth / 2;
			int boxY1 = centerY - boxHeight / 2 - boxHeight - margin;
			if (msg.x > boxX1 && msg.x < boxX1 + boxWidth &&
				msg.y > boxY1 && msg.y < boxY1 + boxHeight)
			{
				currentPage = 2;
			}

			int boxX2 = centerX - boxWidth / 2;
			int boxY2 = centerY - boxHeight / 2;
			if (msg.x > boxX2 && msg.x < boxX2 + boxWidth &&
				msg.y > boxY2 && msg.y < boxY2 + boxHeight)
			{
				currentPage = 3;
			}

			int boxX3 = centerX - boxWidth / 2;
			int boxY3 = centerY - boxHeight / 2 + boxHeight + margin;
			if (msg.x > boxX3 && msg.x < boxX3 + boxWidth &&
				msg.y > boxY3 && msg.y < boxY3 + boxHeight)
			{
				currentPage = 4;
			}

			int boxX4 = centerX - boxWidth / 2;
			int boxY4 = centerY - boxHeight / 2 + 2 * (boxHeight + margin);
			if (msg.x > boxX4 && msg.x < boxX4 + boxWidth &&
				msg.y > boxY4 && msg.y < boxY4 + boxHeight)
			{
				currentPage = 5;
			}
		}
	}
	return;
}
void BeginGame(int diff, int monstersnum)
{
	cleardevice();
	drawMap(diff, monstersnum);
	drawMonster();
	getimage(&map[0], 0, 0, WIDTH, HEIGHT);
	putimage(0, 0, &map[0]);
	GameLoop();
}
void DrawGame1Screen()
{
	putimage(0, 0, &img2);
}
void PutAlphaImage(int x, int y, IMAGE* pSrcImage)
{
	PUTAlphaImage(nullptr, x, y, pSrcImage);
}
void PUTAlphaImage(IMAGE* pDstImage, int x, int y, IMAGE* pSrcImage)
{
	DWORD* pDestBuffer = GetImageBuffer(pDstImage);
	const DWORD* pSrcBuffer = GetImageBuffer(pSrcImage);
	const int srcWidth = pSrcImage->getwidth();
	const int srcHeight = pSrcImage->getheight();
	const int destWidth = pDstImage ? pDstImage->getwidth() : getwidth();
	const int destHeight = pDstImage ? pDstImage->getheight() : getheight();

	int destX = x;
	int destY = y;

	if ((destX + srcWidth < 0) || (destY + srcHeight < 0) || (destX >= destWidth) || (destY >= destHeight))
	{
		return;
	}

	const int width = min(destX + srcWidth, destWidth) - max(destX, 0);
	const int height = min(destY + srcHeight, destHeight) - max(destY, 0);
	if (destX < 0)
	{
		pSrcBuffer -= destX;
		destX = 0;
	}
	if (destY < 0)
	{
		pSrcBuffer -= destY * srcWidth;
		destY = 0;
	}
	pDestBuffer += destWidth * destY + destX;

	for (int i = 0; i < height; i++)
	{
		for (int j = 0; j < width; j++)
		{
			const int alpha = (pSrcBuffer[j] & 0xff000000) >> 24;
			pDestBuffer[j] = ARGB(pSrcBuffer[j], pDestBuffer[j], alpha);
		}

		pDestBuffer += destWidth;
		pSrcBuffer += srcWidth;
	}
}
void InitializePlayerAndResources()
{
	cropImage(&player1, 6, 6, players1);
	cropImage(&player2, 4, 4, players2);

	drawPreMap();

	for (int i = 0; i < 6; i++)
	{
		players_m[i] = mirrorImage(players1[6 + i]);
	}
	for (int i = 0; i < 4; i++)
	{
		effect_m[i] = mirrorImage(players2[4 + i]);
	}

	if (players_m[5] == nullptr || effect_m[3] == nullptr)
	{
		std::exit(EXIT_FAILURE);
	}
}
void PlusKeyClick()
{
	while (1)
	{
		if (haveLvDot)
		{
			if (GetAsyncKeyState(0x31) & 0x8000)
			{
				cyx.maxHealth += 50;
				cyx.lvadddot--;
				break;
			}
			else if (GetAsyncKeyState(0x32) & 0x8000)
			{
				cyx.maxMana += 30;
				cyx.lvadddot--;
				break;
			}
			else if (GetAsyncKeyState(0x33) & 0x8000)
			{
				cyx.minAttack += 5;
				cyx.lvadddot--;
				break;
			}
			else if (GetAsyncKeyState(0x34) & 0x8000)
			{
				cyx.maxAttack += 5;
				cyx.lvadddot--;
				break;
			}
			else if (GetAsyncKeyState(0x35) & 0x8000)
			{
				cyx.defense += 5;
				cyx.lvadddot--;
				break;
			}
			else if (GetAsyncKeyState(0x36) & 0x8000)
			{
				cyx.critChance += 0.05;
				cyx.lvadddot--;
				break;
			}
			else if (GetAsyncKeyState(0x37) & 0x8000)
			{
				cyx.critDamage += 0.1;
				cyx.lvadddot--;
				break;
			}
			else if (GetAsyncKeyState(0x38) & 0x8000)
			{
				cyx.critDamage += 0.1;
				cyx.lvadddot--;
				break;
			}
		}
		Sleep(500);
	}
	if (cyx.lvadddot == 0)
	{
		haveLvDot = false;
	}
}
void HandleKeyboardInput()
{
	if (Operator1(VK_UP, 'W') && people_y > 0)
	{
		whatDirection = 1;
		lastDirection = 1;
	}
	else if (Operator1(VK_DOWN, 'S') && people_y < HEIGHT)
	{
		whatDirection = 2;
		lastDirection = 2;
	}
	else if (Operator1(VK_LEFT, 'A') && people_x > 0)
	{
		whatDirection = 3;
		lastDirection = 3;
	}
	else if (Operator1(VK_RIGHT, 'D') && people_x < WIDTH)
	{
		whatDirection = 4;
		lastDirection = 4;
	}
	else
	{
		whatDirection = 0; // 没有按键时角色静止
	}
	if (GetAsyncKeyState('B') & 0x8000)
	{
		Sleep(300);
		isInventoryOpen = !isInventoryOpen;
	}
}
void DrawGameGraphics(int beginX, int beginY, int i, int mode, IMAGE* map)
{
	cleardevice();
	BeginBatchDraw();
	setfillcolor(BLACK);
	bar(0, 0, WIDTH, HEIGHT);
	HRGN hRgn = CreateEllipticRgn(beginX, beginY, beginX + length, beginY + length);
	setcliprgn(hRgn);

	putimage(beginX, beginY, length, length, map, beginX, beginY); // 方型可见区域
	if (mode == 1)
		movementCheck(beginX, beginY, i);
	else if (mode == 2)
		attackCheck(beginX, beginY, i);

	setcliprgn(nullptr);
	DeleteObject(hRgn);

	if (isInventoryOpen)
	{                                                    // 背包窗口
		int windowX = (WIDTH - window.getwidth()) / 2;   // 计算窗口的X坐标，使其居中
		int windowY = (HEIGHT - window.getheight()) / 2; // 计算窗口的Y坐标，使其居中
		putimage(windowX, windowY, &window);
		cyx.printAttribute(windowX, windowY);
	}

	DrawCharacterInfo();

	FlushBatchDraw();
}
void movementCheck(int beginX, int beginY, int i)
{
	if (whatDirection == 1)
		PutAlphaImage(beginX + 40, beginY + 40, players1[30 + (i % 6)]);
	else if (whatDirection == 2)
		PutAlphaImage(beginX + 40, beginY + 40, players1[18 + (i % 6)]);
	else if (whatDirection == 3)
		PutAlphaImage(beginX + 40, beginY + 40, players_m[5 - i % 6]);
	else if (whatDirection == 4)
		PutAlphaImage(beginX + 40, beginY + 40, players1[6 + (i % 6)]);
	else if (whatDirection == 0)
	{

		switch (lastDirection)
		{
		case 0:
			PutAlphaImage(beginX + 40, beginY + 40, players1[6]);
			lastDirection = 0;
			break;
		case 1:
			PutAlphaImage(beginX + 40, beginY + 40, players1[35]);
			lastDirection = 1;
			break;
		case 2:
			PutAlphaImage(beginX + 40, beginY + 40, players1[23]);
			lastDirection = 2;
			break;
		case 3:
			PutAlphaImage(beginX + 40, beginY + 40, players_m[0]);
			lastDirection = 3;
			break;
		case 4:
			PutAlphaImage(beginX + 40, beginY + 40, players1[11]);
			lastDirection = 4;
			break;
		}
	}
}
void CharacterMovementLogic1()
{
	int L_x = people_x - 50;
	int U_y = people_y - 55;
	int R_x = people_x + PEOPLE_SIZE - 25;
	int D_y = people_y + PEOPLE_SIZE - 40;

	switch (whatDirection)
	{
	case 1: // 向上移动
		U_y -= 4;
		if (!isWall(L_x / CELL_SIZE + 1, U_y / CELL_SIZE + 1) && U_y >= 0)
		{
			people_y = U_y + 55;
		}
		break;
	case 2: // 向下移动
		D_y += 4;
		if (!isWall(L_x / CELL_SIZE + 1, D_y / CELL_SIZE) && D_y <= HEIGHT)
		{
			people_y = D_y - PEOPLE_SIZE + 40;
		}
		break;
	case 3: // 向左移动
		L_x -= 4;
		if (!isWall(L_x / CELL_SIZE + 1, U_y / CELL_SIZE + 1) && L_x >= 0)
		{
			people_x = L_x + 50;
		}
		break;
	case 4: // 向右移动
		R_x += 4;
		if (!isWall(R_x / CELL_SIZE, U_y / CELL_SIZE + 1) && R_x <= WIDTH)
		{
			people_x = R_x + 25 - PEOPLE_SIZE;
		}
		break;
	}
}
void GameLoop()
{
	// 初始化角色和资源
	people_x = entryX * CELL_SIZE;
	people_y = entryY * CELL_SIZE;

	for (int i = 1;; i++)
	{
		int beginX = people_x - 80;
		int beginY = people_y - 120;

		if (!battleInProgress)
		{
			// 角色移动逻辑，仅当不在对战中时允许移动
			CharacterMovementLogic1();
		}

		if (IsPlayerNearExit())
		{
			break;
		}

		// 绘制角色和动画
		if (!IsPlayerNearMonster())
		{
			DrawGameGraphics(beginX, beginY, i, 1, &map[0]);
		}

		else if (IsPlayerNearMonster() && !battleInProgress)
		{
			// 触发对战操作
			battleInProgress = true; // 进入对战状态

			Character myMonster("Monster", STAGES, 200 + STAGES, 200 + STAGES, \
				0, 0, 10 + STAGES*3, 20 + STAGES*3, 10 + STAGES*3 , 0.2, 1.5, 0);

			BattleLoop(beginX, beginY, myMonster);

			if (cyx.health == 0) {
				returnToMain = true;
				cyx.mana = cyx.maxMana;
				cyx.health = cyx.maxHealth;
				break;
			}

			maze[monsterY][monsterX] = 0;

			PutAlphaImage(monsterX, monsterY, &cha);

			saveNewImage(beginX, beginY, i);

			battleInProgress = false; // 退出对战状态
		}
		Sleep(30); // 控制帧率
		// 监听键盘输入并更新方向，仅当不在对战中时允许更新方向
		if (!battleInProgress)
		{
			HandleKeyboardInput();
		}
		cyx.levelUp();
	}
}
int Operator1(char a, char b)
{
	return (GetAsyncKeyState(a) & 0x8000 | GetAsyncKeyState(b) & 0x8000);
}
void cropImage(IMAGE* inputImage, int numCols, int numRows, IMAGE* a[])
{
	int imageWidth = inputImage->getwidth();   // 使用指针访问成员
	int imageHeight = inputImage->getheight(); // 使用指针访问成员

	int cropWidth = imageWidth / numCols;
	int cropHeight = imageHeight / numRows;

	std::vector<IMAGE*> croppedImages;

	for (int y = 0; y < numRows; y++)
	{
		for (int x = 0; x < numCols; x++)
		{
			IMAGE* cropped = new IMAGE;
			putimage(0, 0, inputImage);
			getimage(cropped, x * cropWidth, y * cropHeight, cropWidth, cropHeight);
			croppedImages.push_back(cropped);
		}
	}
	for (int i = 0; i < croppedImages.size(); i++)
	{
		a[i] = croppedImages[i];
	}

	cleardevice();
}
IMAGE* mirrorImage(IMAGE* pImg)
{
	int width = pImg->getwidth();
	int height = pImg->getheight();

	IMAGE* pMirrorImg = new IMAGE(width, height);

	DWORD* pBuffer = GetImageBuffer(pImg);
	DWORD* pMirrorBuffer = GetImageBuffer(pMirrorImg);

	for (int y = 0; y < height; y++)
	{
		for (int x = 0; x < width; x++)
		{
			pMirrorBuffer[y * width + x] = pBuffer[y * width + (width - x - 1)];
		}
	}
	return pMirrorImg;
}
void DrawCharacterInfo()
{
	if (!isInventoryOpen)
	{
		PutAlphaImage(1450, 50, &bag);
	}
	else
	{
		PutAlphaImage(1450, 50, &back);
	}
	setbkmode(TRANSPARENT);
	settextcolor(WHITE);
	BeginBatchDraw();
	// 绘制角色头像
	PutAlphaImage(20, 20, &player_head);

	// 绘制角色等级
	settextstyle(20, 0, _T("宋体"));
	std::wstring levelStr = L"等级: " + std::to_wstring(cyx.level);
	const wchar_t* tcharLevel = levelStr.c_str();
	outtextxy(80, 30, tcharLevel);
	//绘制关卡数
	settextstyle(20, 0, _T("宋体"));
	std::wstring stageStr = L"Stage: " + std::to_wstring(STAGES);
	const wchar_t* tcharStage = stageStr.c_str();
	outtextxy(100, 50, tcharStage);

	// 绘制血条和蓝条外框
	rectangle(20, 80, 220, 90);
	rectangle(20, 100, 220, 110);

	// 绘制血条
	int healthBarWidth = (cyx.health * 200) / cyx.maxHealth; // 根据血量计算宽度
	setfillcolor(RED);
	bar(20, 80, 20 + healthBarWidth, 90);

	// 显示血量信息
	settextstyle(16, 0, _T("宋体"));
	std::wstring healthStr = L"HP:  " + std::to_wstring(cyx.health) + L"/" + std::to_wstring(cyx.maxHealth);
	const wchar_t* tcharHealthStr = healthStr.c_str();
	outtextxy(20, 77, tcharHealthStr);

	// 绘制蓝条
	int manaBarWidth = (cyx.mana * 200) / cyx.maxMana; // 根据蓝量计算宽度
	setfillcolor(BLUE);
	bar(20, 100, 20 + manaBarWidth, 110);

	// 显示蓝量信息
	settextstyle(16, 0, _T("宋体"));
	std::wstring manaStr = L"MP:  " + std::to_wstring(cyx.mana) + L"/" + std::to_wstring(cyx.maxMana);
	const wchar_t* tcharManaStr = manaStr.c_str();
	outtextxy(20, 100, tcharManaStr);

	// 绘制经验条外框
	rectangle(20, 120, 220, 130);

	// 绘制经验条
	int expBarWidth = (cyx.experience * 200) / requiredExp[cyx.level - 1]; // 根据经验值计算宽度
	setfillcolor(GREEN);
	bar(20, 120, 20 + expBarWidth, 130);

	// 显示经验信息
	settextstyle(16, 0, _T("宋体"));
	// settextcolor(BLACK);
	std::wstring expStr = L"EXP:  " + std::to_wstring(cyx.experience) + L"/" + std::to_wstring(requiredExp[cyx.level - 1]);
	const wchar_t* tcharExpStr = expStr.c_str();
	outtextxy(20, 117, tcharExpStr);

	showMassage();

	FlushBatchDraw();
}
void showMassage() {
	if (showSkill1) {
		outtextxy(20, 150, L"您使用了一技能");
		showSkill1 = false;
	}
	if (showSkill2) {
		outtextxy(20, 150, L"您使用了二技能");
		showSkill2 = false;
	}
	if (showSkill3) {
		outtextxy(20, 150, L"您使用了三技能");
		showSkill3 = false;
	}
	if (showCrit) {
		outtextxy(20, 150, L"您触发了暴击");
		showCrit = false;
	}
	if (showDodge) {
		outtextxy(20, 150, L"您触发了闪避");
		showDodge = false;
	}
	if (showKill) {
		outtextxy(20, 150, L"您击败了敌人");
		showKill = false;
	}

}
void attackCheck(int beginX, int beginY, int i)
{
	if (lastDirection == 1)
	{
		PutAlphaImage(beginX + 40, beginY + 40, players2[8 + i % 4]);
	}
	else if (lastDirection == 2)
	{
		PutAlphaImage(beginX + 40, beginY + 40, players2[i % 4]);
	}
	else if (lastDirection == 3)
	{
		PutAlphaImage(beginX + 40, beginY + 40, effect_m[i % 4]);
	}
	else if (lastDirection == 4)
	{
		PutAlphaImage(beginX + 40, beginY + 40, players2[4 + i % 4]);
	}
}
void generateMaze(int complexity)
{
	// 初始化迷宫
	for (int y = 0; y < mazeHeight; ++y)
	{
		for (int x = 0; x < mazeWidth; ++x)
		{
			maze[y][x] = 1;
			visited[y][x] = false;
		}
	}
	// 随机生成迷宫墙壁，使用逐步增加的复杂度系数
	for (int y = 1; y < mazeHeight - 1; y += 2)
	{
		for (int x = 1; x < mazeWidth - 1; x += 2)
		{
			maze[y][x] = 0; // 打通当前格子
			for (int i = 0; i < complexity; ++i)
			{
				int dir = rand() % 4; // 随机选择一个方向
				switch (dir)
				{
				case 0: // 向上
					if (y > 1)
					{
						maze[y - 1][x] = 0;
					}
					break;
				case 1: // 向右
					if (x < mazeWidth - 2)
					{
						maze[y][x + 1] = 0;
					}
					break;
				case 2: // 向下
					if (y < mazeHeight - 2)
					{
						maze[y + 1][x] = 0;
					}
					break;
				case 3: // 向左
					if (x > 1)
					{
						maze[y][x - 1] = 0;
					}
					break;
				}
			}
		}
	}
}
bool isWall(int x, int y)
{
	return maze[y][x] == 1;
}
bool hasPathBetween(int startX, int startY, int endX, int endY)
{
	stack<pair<int, int>> stk;
	stk.push(make_pair(startX, startY));

	while (!stk.empty())
	{
		int x, y;
		tie(x, y) = stk.top();
		stk.pop();

		if (x == endX && y == endY)
		{
			return true;
		}

		if (x < 0 || x >= mazeWidth || y < 0 || y >= mazeHeight || visited[y][x] || (maze[y][x] == 1))
		{
			continue;
		}

		visited[y][x] = true;

		stk.push(make_pair(x - 1, y));
		stk.push(make_pair(x + 1, y));
		stk.push(make_pair(x, y - 1));
		stk.push(make_pair(x, y + 1));
	}
	return false;
}
void drawMaze(int entryX, int entryY, int exitX, int exitY)
{
	std::random_device rd;
	std::mt19937 f(rd());
	std::uniform_int_distribution<> NUM(0, 3);

	for (int y = 0; y < mazeHeight; y++)
	{
		for (int x = 0; x < mazeWidth; x++)
		{
			if (maze[y][x] == 1)
			{
				putimage(x * CELL_SIZE, y * CELL_SIZE, &map_bricks[0]); // 将"1.png"替换为实际图像路径
			}
			else
			{
				if (x == entryX && y == entryY)
				{
					putimage(x * CELL_SIZE, y * CELL_SIZE, &map_bricks[1]); // 将"2.png"替换为实际图像路径
				}
				else if (x == exitX && y == exitY)
				{
					putimage(x * CELL_SIZE, y * CELL_SIZE, &map_bricks[2]); // 将"3.png"替换为实际图像路径
				}
				else
				{
					putimage(x * CELL_SIZE, y * CELL_SIZE, &map_bricks[3]); // 将"4.png"替换为实际图像路径
				}
			}
		}
	}
}
void drawMap(int complexity, int monsternum)
{
	//initgraph(WIDTH, HEIGHT);
	generateMaze(complexity); // 设置复杂度系数为2

	do
	{
		std::random_device rd;
		std::mt19937 f(rd());
		std::uniform_int_distribution<> distX(0, mazeWidth - 1);
		std::uniform_int_distribution<> distY(0, mazeHeight - 1);

		entryX = distX(f);
		entryY = distY(f);
		exitX = distX(f);
		exitY = distY(f);
	} while (isWall(entryX, entryY) || isWall(exitX, exitY) || entryX == exitX && entryY == exitY || !hasPathBetween(entryX, entryY, exitX, exitY));

	maze[entryX][entryY] = 3;
	maze[exitX][exitY] = 4;

	makeMonsters(monsternum);
	drawMaze(entryX, entryY, exitX, exitY);
}
void makeMonsters(int num)
{
	std::random_device rd;
	std::mt19937 f(rd());
	std::uniform_int_distribution<> distX(0, mazeWidth - 1);
	std::uniform_int_distribution<> distY(0, mazeHeight - 1);
	std::uniform_int_distribution<> NUM(0, 3);

	int monsterx, monstery;
	for (int i = 0; i < num;)
	{
		do
		{
			monsterx = distX(f);
			monstery = distY(f);
		} while (monsterx == entryX && monstery == entryY || monsterx == exitX && monstery == exitY);

		if (maze[monstery][monsterx] == 0)
		{
			bool isOverlapping = false;

			for (int dy = -1; dy <= 1; ++dy)
			{
				for (int dx = -1; dx <= 1; ++dx)
				{
					int newX = monsterx + dx;
					int newY = monstery + dy;

					if (newX >= 0 && newX < mazeWidth && newY >= 0 && newY < mazeHeight && maze[newY][newX] == 2)
					{
						isOverlapping = true;
						break;
					}
				}
				if (isOverlapping)
				{
					break;
				}
			}

			if (!isOverlapping)
			{
				maze[monstery][monsterx] = 2;
				++i;
			}
		}
	}
}
bool IsPlayerNearMonster()
{
	// 获取角色和怪兽的坐标
	int playerX = people_x / CELL_SIZE; // 假设CELL_SIZE为格子的大小
	int playerY = people_y / CELL_SIZE;

	// 遍历怪兽位置
	for (int y = 0; y < mazeHeight; y++)
	{
		for (int x = 0; x < mazeWidth; x++)
		{
			if (maze[y][x] == 2) // 怪兽的值为2
			{
				// 计算角色与怪兽的距离
				monsterX = x;
				monsterY = y;
				int distance = abs(playerX - monsterX) + abs(playerY - monsterY);

				// 如果距离小于阈值，认为角色靠近怪兽
				if (distance <= 0) // 你可以根据实际情况调整阈值
				{
					return true;
				}
			}
		}
	}

	return false;
}
void BattleLoop(int beginX, int beginY, Character monsters)
{
	int j = 1;
	// 在这里实现对战逻辑
	while (cyx.health > 0 && monsters.health > 0 && j++)
	{
		if (GetAsyncKeyState(VK_F1) & 0x8000)
		{
			cyx.useSkill1();
			showSkill1 = true;
			usingSkill1 = true;
		}
		if (GetAsyncKeyState(VK_F2) & 0x8000)
		{
			showSkill2 = true;
			cyx.useSkill2(monsters);
			usingSkill2 = true;
		}
		if (GetAsyncKeyState(VK_F3) & 0x8000)
		{
			showSkill3 = true;
			cyx.useSkill3();
		}

		// 角色对怪兽造成伤害

		if (usingSkill1)
		{
			int originalMaxAttack = cyx.maxAttack; // 保存原始最大攻击力
			cyx.maxAttack *= 3;
			monsters.takeDamage(cyx);
			cyx.maxAttack = originalMaxAttack; // 恢复原始最大攻击力
			usingSkill1 = false;               // 不再使用技能1
		}

		else
		{
			if (!usingSkill2)
				monsters.takeDamage(cyx);
		}
		// 怪兽对角色造成伤害
		cyx.takeDamage(monsters);

		// 在控制台或界面上显示战斗过程
		cleardevice();

		for (int i = 0; i < 4; i++)
		{
			DrawGameGraphics(beginX, beginY, i, 2, &map[0]);
			//showMassage();
			Sleep(150);
		}
		Sleep(400);
	}
	showKill = true;
	cyx.gainExperience(monsters);

}
void drawMonster()
{
	std::random_device rd;
	std::mt19937 f(rd());
	std::uniform_int_distribution<> NUM(0, 3);
	for (int y = 0; y < mazeHeight; y++)
	{
		for (int x = 0; x < mazeWidth; x++)
		{
			if (maze[y][x] == 2)
			{
				int n = NUM(f);
				PutAlphaImage(x * CELL_SIZE, y * CELL_SIZE, &monster[n]);
			}
		}
	}
}
void saveNewImage(int beginX, int beginY, int i)
{
	BeginBatchDraw();
	cleardevice();
	putimage(0, 0, &map[0]);
	PutAlphaImage(monsterX * CELL_SIZE, monsterY * CELL_SIZE, &cha);
	getimage(&map[0], 0, 0, WIDTH, HEIGHT);
	DrawGameGraphics(beginX, beginY, i, 1, &map[0]);
}
bool IsPlayerNearExit()
{
	// 获取角色和出口的坐标
	int playerX = people_x / CELL_SIZE;
	int playerY = people_y / CELL_SIZE;

	int distance = abs(playerX - exitX) + abs(playerY - exitY);

	// 如果距离小于阈值，认为角色靠近怪兽
	if (distance <= 0) // 你可以根据实际情况调整阈值
	{
		return true;
	}

	return false;
}
void prepareGame()
{

	putimage(0, 0, &map[2]);

	prepareLoop();

}
void drawPreMap()
{
	cleardevice();
	for (int y = 0; y < mazeHeight; y++)
	{
		for (int x = 0; x < mazeWidth; x++)
		{
			if (x < 2 || x >= mazeWidth - 2 || y < 2 || y >= mazeHeight - 2)
			{
				putimage(x * CELL_SIZE, y * CELL_SIZE, &map_bricks[3]); // 外部两圈填充map_bricks[0]
			}
			else if (x < 3 || x >= mazeWidth - 3 || y < 3 || y >= mazeHeight - 3)
			{
				putimage(x * CELL_SIZE, y * CELL_SIZE, &map_bricks[0]); // 第三圈填充map_bricks[1]
			}
			else
			{
				putimage(x * CELL_SIZE, y * CELL_SIZE, &map_bricks[3]);
			}
		}
	}
	
	PutAlphaImage((WIDTH - FrameWidth) / 3, 380, &word[0]);
	PutAlphaImage((WIDTH - FrameWidth) /3, (HEIGHT + FrameWidth) / 2, &word[1]);
	PutAlphaImage((WIDTH - FrameWidth) /3, (HEIGHT - FrameWidth) / 8, &word[2]);
	getimage(&map[2], 0, 0, WIDTH, HEIGHT);

	cleardevice();
}
void prepareLoop()
{
	people_x = 4 * CELL_SIZE;
	people_y = 4 * CELL_SIZE;

	for (int i = 1;; i++)
	{
		int beginX = people_x - 80;
		int beginY = people_y - 120;

		CharacterMovementLogic2();

		if ((GetAsyncKeyState('N') & 0x8000) || returnToMain)
		{
			break;
		}

		if ((GetAsyncKeyState(VK_ESCAPE) & 0x8000))
		{
			isWindowBack = true;
			Sleep(50);
		}

		// 绘制角色和动画
		cleardevice();
		BeginBatchDraw();

		putimage(0, 0, &map[2]); // 方型可见区域
		movementCheck(beginX, beginY, i);

		if (isInventoryOpen)
		{                                                    // 背包窗口
			int windowX = (WIDTH - window.getwidth()) / 2;   // 计算窗口的X坐标，使其居中
			int windowY = (HEIGHT - window.getheight()) / 2; // 计算窗口的Y坐标，使其居中
			putimage(windowX, windowY, &window);
			cyx.printAttribute(windowX, windowY);
			//PlusKeyClick();
			//continue;
		}

		DrawCharacterInfo();

		EndBatchDraw();

		if (isWindowBack)
		{
			int windowX = (WIDTH - windowback.getwidth()) / 2;   // 计算窗口的X坐标，使其居中
			int windowY = (HEIGHT - windowback.getheight()) / 2; // 计算窗口的Y坐标，使其居中

			putimage(windowX, windowY, &windowback);
			while (1)
			{
				if ((GetAsyncKeyState('X') & 0x8000))
				{
					Sleep(50);
					isWindowBack = false;
					break;
				}
				else if ((GetAsyncKeyState('Y') & 0x8000))
				{
					isWindowBack = false;
					returnToMain = true;
					break;
				}
				Sleep(50);
			}
		}
		Sleep(30); // 控制帧率
		// 监听键盘输入并更新方向，仅当不在对战中时允许更新方向
		HandleKeyboardInput();
	}
}
void CharacterMovementLogic2()
{
	switch (whatDirection)
	{
	case 1: // 向上移动
		if (people_y >= 3 * CELL_SIZE)
		{
			people_y -= 4;
		}
		break;
	case 2: // 向下移动
		if (people_y < HEIGHT - 4 * CELL_SIZE)
		{
			people_y += 4;
		}
		break;
	case 3: // 向左移动
		if (people_x >= 3 * CELL_SIZE)
		{
			people_x -= 4;
		}
		break;
	case 4: // 向右移动
		if (people_x < WIDTH - 4 * CELL_SIZE)
		{
			people_x += 4;
		}
		break;
	}
}

